<template>
  <n-modal
    :show="props.visible"
    preset="card"
    :title="props.data?.menuId ? '修改用户' : '添加用户'"
    style="width: 640px"
    @after-enter="handleOpen"
    @close="handleClose"
  >
    <n-form ref="formRef" :model="form" label-placement="left" :label-width="90" :rules="rules">
      <n-form-item label="用户昵称" path="nickName">
        <n-input v-model:value="form.nickName" placeholder="请输入用户昵称" clearable />
      </n-form-item>

      <n-grid cols="2" :x-gap="30">
        <n-form-item-gi label="手机号码" path="phonenumber">
          <n-input v-model:value="form.phonenumber" placeholder="请输入手机号码" clearable />
        </n-form-item-gi>

        <n-form-item-gi label="邮箱" path="email">
          <n-input v-model:value="form.email" placeholder="请输入邮箱" clearable />
        </n-form-item-gi>

        <n-form-item-gi v-if="!form.userId" label="用户名称" path="userName">
          <n-input
            v-model:value="form.userName"
            placeholder="请输入用户名称"
            clearable
            autocomplete="off"
          />
        </n-form-item-gi>

        <n-form-item-gi v-if="!form.userId" label="用户密码" path="password">
          <n-input
            v-model:value="form.password"
            type="password"
            placeholder="请输入用户密码"
            show-password-on="click"
          />
        </n-form-item-gi>

        <n-form-item-gi label="用户性别">
          <n-radio-group v-model:value="form.sex">
            <template v-for="item in dicts.sys_user_sex" :key="item.value">
              <n-radio :value="item.value">{{ item.label }}</n-radio>
            </template>
          </n-radio-group>
        </n-form-item-gi>

        <n-form-item-gi label="状态">
          <n-radio-group v-model:value="form.status">
            <template v-for="item in dicts.sys_normal_disable" :key="item.value">
              <n-radio :value="item.value">{{ item.label }}</n-radio>
            </template>
          </n-radio-group>
        </n-form-item-gi>

        <n-form-item-gi label="岗位">
          <n-select
            v-model:value="form.postIds"
            multiple
            placeholder="请选择岗位"
            :options="postOptions"
          />
        </n-form-item-gi>

        <n-form-item-gi label="角色">
          <n-select
            v-model:value="form.roleIds"
            multiple
            placeholder="请选择角色"
            :options="roleOptions"
          />
        </n-form-item-gi>
      </n-grid>

      <n-form-item label="备注" path="remark">
        <n-input v-model:value="form.remark" type="textarea" placeholder="请输入内容" clearable />
      </n-form-item>
    </n-form>

    <template #footer>
      <n-space justify="end">
        <n-button @click="handleClose">取消</n-button>
        <n-button type="primary" @click="submitCallback" :loading="loading" :disabled="loading">
          确定
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import { addUser, getUser, updateUser } from '@/apis/system/user';
import { useDict } from '@/hooks/useDict';
import { useForm } from '@/hooks/useForm';
import { useMessage } from 'naive-ui';
import { computed, ref } from 'vue';

const emits = defineEmits(['close']);
const props = defineProps<{ visible: boolean; data: any }>();
const data = computed(() => props.data);
const loading = ref(false);
const message = useMessage();
// 岗位options
const postOptions = ref([]);
// 角色options
const roleOptions = ref([]);

const { form, formRef, reset, setForm, validate } = useForm({
  userId: null,
  userName: null,
  nickName: null,
  password: null,
  phonenumber: null,
  email: null,
  sex: null,
  status: '0',
  postIds: [],
  roleIds: [],
  remark: null,
});

const rules = ref({
  userName: [
    { required: true, message: '用户名称不能为空' },
    {
      min: 2,
      max: 20,
      message: '用户名称长度必须介于 2 和 20 之间',
      trigger: 'blur',
    },
  ],
  nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  password: [
    { required: true, message: '用户密码不能为空', trigger: 'blur' },
    {
      min: 5,
      max: 20,
      message: '用户密码长度必须介于 5 和 20 之间',
      trigger: 'blur',
    },
  ],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change'],
    },
  ],
  phonenumber: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
});
// 获取字典：用户状态、性别
const { dicts } = useDict('sys_normal_disable', 'sys_user_sex');

// 打开弹窗回调
const handleOpen = async () => {
  if (data.value) {
    setForm(data.value);
  }
  const res: any = await getUser(data.value?.userId || '');
  if (res.code == 200) {
    postOptions.value = res.data.posts.map((item: any) => ({
      label: item.postName,
      value: item.postId,
      disabled: item.status === '1',
    }));
    roleOptions.value = res.data.roles.map((item: any) => ({
      label: item.roleName,
      value: item.roleId,
      disabled: item.status === '1',
    }));
    if (data.value?.userId) {
      // 编辑状态设置用户postIds、roleIds
      setForm({
        postIds: res.data.postIds,
        roleIds: res.data.roleIds,
      });
    }
    console.log('---->', postOptions.value);
  }
};

const handleClose = (needRefresh = false) => {
  reset();
  emits('close', { needRefresh });
};

const submitCallback = (e: MouseEvent) => {
  e.preventDefault();
  formRef.value?.validate(async (errors) => {
    if (errors) {
      return;
    }
    loading.value = true;
    console.log('---->', form);
    try {
      let res: any;
      if (data.value?.userId) {
        res = await updateUser(form);
      } else {
        res = await addUser(form);
      }
      if (res.code == 200) {
        message.success(data.value?.menuId !== undefined ? '修改成功' : '添加成功');
        handleClose(true);
      }
    } catch (error) {
    } finally {
      loading.value = false;
    }
  });
};
</script>

<style lang="less" scoped></style>
